package com.yun.util.kafka_es.kafkaTest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Enumeration;


public class SystemUtil {
	final static Logger logger = LoggerFactory.getLogger(SystemUtil.class);

	public static long getUsableSpace(String path) {
		File diskPartition = new File(path);
		if (diskPartition.exists())
			return diskPartition.getUsableSpace();
		else
			return -1;
	}

	public static long getTotalSpace(String path) {
		File diskPartition = new File(path);
		if (diskPartition.exists())
			return diskPartition.getTotalSpace();
		else
			return -1;
	}

	public static String getServerIp() {
		String SERVER_IP = null;
		try {
			Enumeration<?> netInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
				Enumeration<InetAddress> addr = ni.getInetAddresses();
				while (addr.hasMoreElements()) {
					ip = (InetAddress) addr.nextElement();
					SERVER_IP = ip.getHostAddress();
					if (!ip.isLoopbackAddress() && Isipv4(SERVER_IP)) {
						return SERVER_IP;
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}

		return SERVER_IP;
	}

	public static boolean Isipv4(String ipv4) {
		if (ipv4 == null || ipv4.length() == 0) {
			return false;// 字符串为空或者空串
		}
		String[] parts = ipv4.split("\\.");// 因为java doc里已经说明, split的参数是reg, 即正则表达式, 如果用"|"分割, 则需使用"\\|"
		if (parts.length != 4) {
			return false;// 分割开的数组根本就不是4个数字
		}
		for (int i = 0; i < parts.length; i++) {
			try {
				int n = Integer.parseInt(parts[i]);
				if (n < 0 || n > 255) {
					return false;// 数字不在正确范围内
				}
			} catch (NumberFormatException e) {
				return false;// 转换数字不正确
			}
		}
		return true;
	}

	public static void writeFile(String filePath, String content) throws IOException {
		Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"));
		writer.write(content);
		writer.flush();
		writer.close();
	}

	public static void writeFileIfNotExist(String filePath,String content) throws IOException{
		File f = new File(filePath);
		if(f.exists()){
			return;
		}else{
			writeFile(filePath,content);
		}
	}

	public static String readFile(String filePath) throws IOException {
		File file = new File(filePath);
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		FileInputStream in = new FileInputStream(file);
		in.read(filecontent);
		in.close();
		return new String(filecontent, "UTF-8");
	}

	public static byte[] getByteFromFile(String filePath) throws IOException {
		File file = new File(filePath);
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		FileInputStream in = new FileInputStream(file);
		in.read(filecontent);
		in.close();
		return filecontent;
	}

	public static String readResourceFile(String resourcePath) {
		InputStream in = SystemUtil.class.getResourceAsStream(resourcePath);
		try {
			if (in != null) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				int n = 0;
				byte[] bs = new byte[1024 * 1024];
				while ((n = in.read(bs)) != -1) {
					out.write(bs, 0, n);
				}
				out.close();
				in.close();
				return out.toString("UTF-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static void writeObject2File(String filePath, Object obj) throws IOException {
		try (
				ObjectOutputStream oo = new ObjectOutputStream(
						new BufferedOutputStream(new FileOutputStream(new File(filePath))));
		) {
			oo.writeObject(obj);
			oo.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Object readObjectFromFile(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
		try {
			Object obj = in.readObject();
			return obj;
		} finally {
			in.close();
		}

	}

	private static String[] run(Process p,boolean silent) {
		int b;
		try (InputStream error = p.getErrorStream(); ByteArrayOutputStream buffError = new ByteArrayOutputStream(); InputStream input = p.getInputStream(); ByteArrayOutputStream buff = new ByteArrayOutputStream()) {
			while ((b = error.read()) != -1) {
				buffError.write(b);
			}
			String buffErrStr = buffError.toString();
			if (buffErrStr != null && buffErrStr.length() > 0) {
				logger.error(buffErrStr);
			}

			while ((b = input.read()) != -1) {
				buff.write(b);
			}
			String buffStr = buff.toString();
			if(!silent)
				logger.info(buffStr);
			return new String[]{buffStr, buffErrStr};
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return new String[]{"", e.getMessage()};
		}
	}

	/**
	 * 执行命令
	 * @param cmd 命令字符串
	 * @return String[] 数组[0]为正常输出，数组[1]为error输出
	 */
	public static String[] run(String cmd) {
		logger.info("执行命令：{}", cmd);
		try {
			Process p = Runtime.getRuntime().exec(cmd);
			return run(p,false);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return new String[]{"", e.getMessage()};
		}
	}

	/**
	 * 执行命令
	 * @param cmd 命令数组
	 * @return String[] 数组[0]为正常输出，数组[1]为error输出
	 */
	public static String[] run(String[] cmd) {
		try {
			logger.info("执行命令：" + Arrays.toString(cmd));
			Process p = Runtime.getRuntime().exec(cmd);
			return run(p,false);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return new String[2];
		}
	}

	public static String[] runSilent(String[] cmd) {
		try {
			Process p = Runtime.getRuntime().exec(cmd);
			return run(p,true);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return new String[2];
		}
	}

	public static void writeFile(String filePath, byte[] bytes) {
		FileOutputStream writer = null;
		try {
			writer = new FileOutputStream(filePath);
			writer.write(bytes);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
